/**
 * User: alesj
 * Date: 15.1.2006
 * Time: 14:35:24
 * 
 * (C) Genera Lynx d.o.o.
 */

package com.alesj.blueberry.spring.sms.impl;

import com.alesj.blueberry.spring.validation.ValidationResult;

import java.util.regex.Pattern;

/**
 * @author <a href="mailto:ales.justin@genera-lynx.com">Ales Justin</a>
 */
public class MessageRegExpValidator
        extends AbstractValidator
        implements MessageRegExpValidatorMBean {

    private Pattern pattern;

    public MessageRegExpValidator(String regexp) {
        setKey("validator.invalid.message");
        this.pattern = Pattern.compile(regexp);
    }

    public ValidationResult validate(long timestamp, String number, String message) {
        String preparedMessage = prepareMessage(message);
        if (!pattern.matcher(preparedMessage).find()) {
            return new ValidationResult(getKey(), new Object[]{message});
        }
        return null;
    }

    //add ' ' at the end for regexp matching
    protected String prepareMessage(String message) {
        return message.trim() + " ";
    }

    public String getPattern() {
        return pattern.pattern();
    }

    public void setPattern(String pattern) {
        this.pattern = Pattern.compile(pattern);
    }

}
